package com.potevio.simulator.controller;


import com.potevio.simulator.common.CommonFlag;
import com.potevio.simulator.common.GetHexMessage;
import com.potevio.simulator.common.R;
import com.potevio.simulator.config.MsgTypeConst;
import com.potevio.simulator.entity.SiginMsg0x10;
import com.potevio.simulator.heart.HeartbeatClient;
import com.potevio.simulator.strategy.impl.Deal79Command;
import com.potevio.simulator.task.CommonTask;
import com.potevio.simulator.util.HexUtil;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.commons.nullanalysis.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("client")
public class ClientController {

    private static final Logger log = LoggerFactory.getLogger(ClientController.class);

    /**
     * 启动netty客户端
     *
     * @throws InterruptedException
     */
    @RequestMapping("/startNettyClient")
    @ResponseBody
    public R startNettyClient(String serverip, String serverPort, String deviceNo, String version, String deviceGunNum) throws InterruptedException {
        if(StringUtils.isBlank(serverip) || StringUtils.isBlank(serverPort) || StringUtils.isBlank(deviceNo) || StringUtils.isBlank(version)){
            return R.error();
        }
        HeartbeatClient.host = serverip;
        HeartbeatClient.nettyPort = Integer.parseInt(serverPort);
        SiginMsg0x10.chargingPile = deviceNo;
        //桩协议设置
        CommonFlag.version = version;
        CommonFlag.messageSendFlag = Boolean.TRUE;
        //枪数量设置
        if("3.4a".equals(version)){
            HeartbeatClient.chargeGunNum = "02";
        }else if("3.4".equals(CommonFlag.version)){
            HeartbeatClient.chargeGunNum = "01";
        }
        new HeartbeatClient().start();
        return R.ok();
    }

    /**
     * 停止netty客户端
     *
     * @throws InterruptedException
     */
    @RequestMapping("/stopNettyClient")
    @ResponseBody
    public R stopNettyClient() throws InterruptedException {
        if(CollectionUtils.isEmpty(MsgTypeConst.CHARGE_POSTS)){
            CommonFlag.messageSendFlag = Boolean.FALSE;
        }
        new HeartbeatClient().closeConnect();
//        EchoClientHandle.channelGroup.writeAndFlush("asdf");
        return R.ok();
    }


    /**
     * 发送70报文,刷卡充电
     */
    @RequestMapping("/send70Msg")
    @ResponseBody
    public R send70Msg(String cardNumber, String chargeNum)  {
        try {

            HeartbeatClient.chargeType = "1";
            Map<String, LinkedHashMap<String, String>> listMap = null;
            if("3.4a".equals(CommonFlag.version) || "3.4a1".equals(CommonFlag.version)  ){
                listMap = new GetHexMessage().getDataDomain(MsgTypeConst.CHARGE_ACCOUNT_SELECT_MSG,chargeNum);

            }else{
                listMap = new GetHexMessage().getDataDomain(MsgTypeConst.CHARGE_ACCOUNT_SELECT_MSG);

            }
            if("3.4a1".equals(CommonFlag.version)  ){
                listMap.get("0x70").put("userId","0100");
            }
            listMap.put("0x70", deal70(listMap.get("0x70"), cardNumber, chargeNum));
            HeartbeatClient.channel.writeAndFlush(listMap);
            // 设置充电桩状态为充电中
            HeartbeatClient.chargingPileState = 1;
            MsgTypeConst.CHARGE_POSTS.add(chargeNum);
            return R.ok();
        } catch (Exception e) {
            log.error("发送0x70异常信息：", e);

            return R.error();
        }
    }

    /**
     * 处理70报文
     *
     * @param map
     * @return
     */
    public LinkedHashMap<String, String> deal70(LinkedHashMap<String, String> map, String cardNumber, String chargeNum) throws ParseException {
        Set<String> stringSet = map.keySet();
        Iterator<String> iterator = stringSet.iterator();
        while(iterator.hasNext()){
            String key = iterator.next();
            String value = map.get(key);
            if ("cardNumber".equals(key)) {
                value = HexUtil.ascii2Hex(cardNumber);
            }

            map.put(key, value);
        }
        return map;
    }

    /**
     * 停止70报文充电
     */
    @RequestMapping("/stop70Msg")
    @ResponseBody
    public R stop70Msg(String chargeNum)  {
        try {
            CommonFlag.chargeNum = chargeNum;
            Deal79Command.date = new Date();
            // 修改充电桩状态
            new CommonTask().updateChargeState();
            return R.ok();
        } catch (Exception e) {
            log.error("发送0x70异常信息：", e);
            return R.error();
        }

    }

    /**
     * 获取充电状态
     * @return
     */
    @RequestMapping("/getChargeState")
    @ResponseBody
    public int getChargeState(){
        return HeartbeatClient.chargingPileState;
    }

    /**
     * 16进制字符串添加空格
     *
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {
        String hexStr = "FAF53E80303400000000020501000000000000000000000000000000000000800C00000000010901000000000000000000000000000000000000800C0000000003";
        int num = 0;
        int strl = hexStr.length();
        StringBuffer stringBuffer = new StringBuffer();
        while (num < strl) {
            stringBuffer.append(hexStr.substring(num, num + 2)).append(" ");
            num = num + 2;
        }
        System.out.println(stringBuffer);
//        BigDecimal bg = new BigDecimal("4.06");
//        float kk = bg.floatValue();
//        System.out.println(Integer.toHexString(Float.floatToIntBits(kk)));
//        for (int i = 0; i < 2; i++) {
//            System.out.println("当前时间：" + System.currentTimeMillis());
//            System.out.println("睡眠：" + 10 + "秒");
//            Thread.sleep(10*1000);
//        }
//        try{
//            String a = null;
//            System.out.println(a.toString());
//        }catch (Exception e){
//            log.error("异常，{}", e.getMessage(),e);
//        }
    }

}
